/*
RetroLeague - Mobile application for The Retro League Podcast
Copyright (C) 2010-2013 Hugues Johnson

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See
the GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software 
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 */

package com.huguesjohnson.retroleague.util;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.util.Log;

public class BruteForceDateParser{
	   private static BruteForceDateParser instance=null;
	   private static Pattern datePatternDefault;
	   private static DateFormat dateFormatterDefault=null;
	   private static DateFormat dateFormatterRssGmt=null;
	   private static DateFormat dateFormatterRssGmtRfc822=null;

	   protected BruteForceDateParser(){ }

	   public static synchronized BruteForceDateParser getInstance(){
		   if(instance==null){
		         instance=new BruteForceDateParser();
		         synchronized(BruteForceDateParser.class){
		        	 datePatternDefault=Pattern.compile("[0-9]{1,2} [a-zA-Z]{3} [0-9]{4}");
		        	 dateFormatterDefault=new SimpleDateFormat("dd MMM yyyy",Locale.US);
		        	 dateFormatterRssGmt=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss zzz",Locale.US);
		        	 dateFormatterRssGmtRfc822=new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z",Locale.US);
		         }
		   }
		   return(instance);
	   }

	   public Date parseDate(String sDate){
		   Date date=null;
		   try{
			   date=dateFormatterRssGmt.parse(sDate);
			   return(date);
		   }catch(Exception x){ }
		   try{
			   date=dateFormatterRssGmtRfc822.parse(sDate);
			   return(date);
		   }catch(Exception x){ }
		   try{
				Matcher dateMatcher=datePatternDefault.matcher(sDate);
				if(dateMatcher.find()){
					String smallerDateString=sDate.substring(dateMatcher.start(),dateMatcher.end());
					date=dateFormatterDefault.parse(smallerDateString);
					return(date);
				}
		   }catch(Exception x){ }
		   Log.e("BruteForceDateParser","Input date did not match any supported formats, sDate="+sDate);
		   return(date);
	   }
}